<?php defined('SYSPATH') or die('No direct script access.');

class kotemp_Core {
	/**
	* Writes file
	* 
	* @param  string  Filename - with path included ($file)
	* @param  string  Output buffer contents ($output_buffer)
	*/
	public static function write($file, $output_buffer)
	{
		// Create directory string
		$count = strrpos($file, '/');
		$dir = substr($file, 0, $count);
		
		if (!is_dir($dir))
		{
			if ( ! $d = mkdir($dir, 0777, TRUE))
				throw new Kohana_Exception('kotemp.dir_error');
		}
		
		if (!$fp = fopen($file, 'w'))
			throw new Kohana_Exception('kotemp.write_error');

		if (fwrite($fp, $output_buffer) === FALSE)
			throw new Kohana_Exception('kotemp.write_permissions');

		fclose($fp);

		@chmod($file, 0666);
	}
	
	/**
	* Determines the file path based on where the view file came from
	* 
	* @param  string  Name of the template ($template_name)
	* @return string  Filename and path
	*/
	public static function parsed_file_name($template_name)
	{
		$template_array = str_split($template_name, strlen(DOCROOT));
		
		$subdir = $template_array[1];
		
		return Kohana::config('kotemp.parsed_file_path').$subdir;
	}
	
	/**
	* Checks if templating system is on
	* 
	* @return  string  Status of system
	*/
	public static function check_if_on()
	{
		return Kohana::config('kotemp.status');
	}
}